package com.android.thelastnoet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.thelastnoet.bean.Note;
import com.android.thelastnoet.db.NoteMapper;
import com.android.thelastnoet.utils.CommonUtil;
import com.android.thelastnoet.utils.SoftKeyBoardListener;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.Date;

public class EditActivity extends AppCompatActivity {

    private String TAG = "EditActivity";
    NoteMapper noteMapper = NoteMapper.getNoteMapper(this);

    Note note = new Note(); //作为存入数据库的对象
    Note transferNote = new Note();   //作为判断中的传输数据对象
    String groupName="未分组";   //分组名
    String state;   //状态

    EditText edit_title_et, edit_content_et;
    Toolbar toolbar;
    LinearLayout toolbar_bottom;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        edit_title_et = findViewById(R.id.edit_title_et);
        edit_content_et = findViewById(R.id.edit_content_et);
        toolbar = findViewById(R.id.toolbar_edit);
        toolbar_bottom=findViewById(R.id.toolbar_bottom);

        /*初始化数据*/
        initData();

        /*设置toolbar*/
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);   //给左上角图标的左边加上一个返回的图标
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);  //给左上角图标的左边加上一个返回的图标
        getSupportActionBar().setDisplayShowTitleEnabled(false);    //去除标题
        toolbar.setNavigationOnClickListener(v -> {
            String title = edit_title_et.getText().toString();
            String content = edit_content_et.getText().toString();
            transferNote.setTitle(title);
            transferNote.setContent(content);

            boolean isSave = isSave(transferNote);
            if (isSave) {
                saveNote();
            }
            finish();
        });
    }

    /*接收主活动传入的信息 并初始化该活动需要的数据*/
    private void initData() {
        Intent intent = getIntent();
        state = intent.getStringExtra("state");
        if (state.equals("new")) {
            /*为新建便签*/
            groupName = getIntent().getStringExtra("groupName");
            if (groupName.equals("全部")) {
                groupName = "未分组";
            }
            edit_content_et.setFocusable(true);     //获取焦点
        } else {
            /*为已有便签 */
            Bundle bundle = intent.getBundleExtra("data");
            transferNote = (Note) bundle.getSerializable("Note");

            edit_title_et.setText(transferNote.getTitle());
            edit_content_et.setText(transferNote.getContent());
            edit_content_et.setSelection(transferNote.getContent().length());   //将光标移动至文字末尾
            SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
                @Override
                public void keyBoardShow(int height) {
                    toolbar_bottom.setVisibility(View.VISIBLE);
                }
                @Override
                public void keyBoardHide(int height) {
                    toolbar_bottom.setVisibility(View.GONE);
                    edit_content_et.clearFocus();
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /*退出该activity时自动保存便签*/
            transferNote.setTitle(edit_title_et.getText().toString());
            transferNote.setContent(edit_content_et.getText().toString());
            boolean isSave = isSave(transferNote);
            if (isSave) {
                saveNote();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /*判断便签是否有内容需要保存*/
    public boolean isSave(Note transferNote) {
        boolean result = true;
        if (transferNote.getContent().trim().equals("") & transferNote.getTitle().equals("")) {
            /*如果标题和内容都为空*/
            Log.d(TAG, "空");
            if (state.equals("edit")) {
                /*已存在的便签则删除*/
                noteMapper.deleteNote(transferNote);
                Toast.makeText(this, "便签内容为空 已删除", Toast.LENGTH_SHORT).show();

            } else if (state.equals("new")) {
                /*新建中的则不做操作*/
                Toast.makeText(this, "未输入内容 不保存", Toast.LENGTH_SHORT).show();
            }
            result = false;
        }
        Log.d(TAG, String.valueOf(result));
        return result;
    }

    /*保存便签*/
    public void saveNote() {
        String title = edit_title_et.getText().toString();
        String content = edit_content_et.getText().toString();
//        Log.d(TAG, "title->" + title + " content->" + content);
        note.setTitle(title);
        note.setContent(content);
        note.setSubContent("空");
        note.setCreateTime(CommonUtil.date2string(new Date()));
        note.setGroupName(groupName);
//        Log.d(TAG," "+groupName);
        if (state.equals("new")) {
            noteMapper.addNote(note);
        } else {
            /*将已有便签id设入note*/
            note.setId(transferNote.getId());
            noteMapper.updateNote(note);
            Log.d(TAG,noteMapper.getNoteById(transferNote.getId()).getGroupName());
        }
    }

    /*创建Menu菜单的项目*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.edit_bar_menu, menu);
        return true;
    }

    /*处理菜单被选中运行后的事件处理*/
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete:
                new MaterialAlertDialogBuilder(EditActivity.this)
                        .setTitle("系统提示：")
                        .setMessage("确定要删除该便签吗？")
                        .setNegativeButton("取消", (dialog, which) -> {

                        }).setPositiveButton("确定", (dialog, which) -> {
                    noteMapper.deleteNote_F(transferNote.getId());
                    finish();
                }).show();
                break;
            case R.id.setLock:
                groupName = "私密便签";
                saveNote();
                Toast.makeText(this, "便签已设为私密，主页下拉查看", Toast.LENGTH_SHORT).show();
                finish();
                break;
            case R.id.share:
                Intent intent_share = new Intent(Intent.ACTION_SEND);
                intent_share.setType("text/plain");
                intent_share.putExtra(Intent.EXTRA_TEXT, transferNote.getTitle()+transferNote.getContent());
                startActivity(intent_share.createChooser(intent_share,"分享到"));
                break;
            case R.id.setRemind:
                Toast.makeText(this, "暂未实现", Toast.LENGTH_SHORT).show();
                break;
            case R.id.notLock:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}

//            Log.d(TAG,"BACK一下");

//            Log.d(TAG, "title->" + transferNote.getTitle() + " content->" + transferNote.getContent());

/*          int id = (int)
            Note note = noteMapper.getNoteById(id);
            String noteContent = note.getContent();
            Log.d(TAG, "id是 " + id+" 内容是 "+noteContent);*/

 /*
        * transferNote.getContent() == null & transferNote.getContent().trim().equals("")
                & transferNote.getTitle() == null & transferNote.getTitle().equals("")
        *   Log.d(TAG, "con_null--" + (transferNote.getContent() == null));
            Log.d(TAG, "con_equal--" + transferNote.getContent().trim().equals(""));
            Log.d(TAG, "title_null--" + (transferNote.getTitle() == null));
            Log.d(TAG, "title_equal--" + transferNote.getTitle().trim().equals(""));
        */


/*            Note note_u = noteMapper.getNoteById(transferNote.getId());
            String noteContent = note_u.getContent();
            String createTime = note_u.getCreateTime();
            Log.d(TAG, "id是 " + note_u.getId() + " 内容是 " + noteContent + "时间是 " + createTime);*/